package com.liruirui.springboot_exam.controller;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.liruirui.springboot_exam.config.AjaxResult;
import com.liruirui.springboot_exam.entity.Movies;
import com.liruirui.springboot_exam.service.IMoviesService;
import com.liruirui.springboot_exam.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liruirui
 * @since 2022-02-09
 */
@Slf4j
@RestController
@RequestMapping("/movies")
public class MoviesController {

    @Autowired
    IMoviesService moviesService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @RequestMapping("/list")
    public AjaxResult list(Movies movies, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize){
        PageInfo<Movies> info = moviesService.getList(movies,pageNum,pageSize);
        return AjaxResult.ok(info);
    }

    @RequestMapping("/add")
    public AjaxResult add(Movies movies) throws InterruptedException {
        Thread.sleep(2000);
        String uri = WebUtils.getRequest().getRequestURI();
        String s = UUID.randomUUID().toString();
        String token = uri;
        if (redisTemplate.opsForValue().setIfAbsent(token,token,3, TimeUnit.SECONDS)) {//提交
            //默认未审核
            movies.setAId(2);
            moviesService.saveOrUpdate(movies);//添加
            return AjaxResult.ok();
        }
        //重复提交
        return AjaxResult.err(405,"已提交,请勿重复提交");
    }

    @RequestMapping("/updateStatus")
    public AjaxResult updateStatus(Movies movies){
        moviesService.saveOrUpdate(movies);//修改状态
        Movies movies1 = moviesService.getById(movies.getId());
        kafkaTemplate.send("topic1","movies", JSON.toJSONString(movies1));//kafka发送
        return AjaxResult.ok();
    }

    @RequestMapping("/toUpdate")
    public AjaxResult toUpdate(Integer id){//回显
        return AjaxResult.ok(moviesService.getByIdMovie(id));
    }

}
